<template>
  <div class="add-teacher-tree">
    <div class="left">
      <div class="checked-area">
        <div class="title">老师</div>
        <div
          class="item"
          v-for="item in selectedTeacherList"
          :key="item.userId"
        >
          <span class="label">{{ item.userName }}</span>
          <a-icon
            class="icon"
            type="close"
            @click="delCheckedEvt(item.userId, 'T', item.departmentId)"
          />
        </div>
        <div class="title">学生</div>
        <div
          class="item"
          v-for="item in selectedStudentList"
          :key="item.userId"
        >
          <span class="label">{{ item.userName }}</span>
          <a-icon
            class="icon"
            type="close"
            @click="delCheckedEvt(item.userId, 'S', item.gradeId)"
          />
        </div>
        <!-- <div class="title">角色</div>
        <div class="item" v-for="item in selectedRoleList" :key="item.userId">
          <span class="label">{{ item.roleName }}</span>
          <a-icon
            class="icon"
            type="close"
            @click="delCheckedEvt(item.roleCode)"
          />
        </div> -->
      </div>
    </div>
    <div class="right">
      <div class="tree">
        <a-tabs default-active-key="1" size="small">
          <a-tab-pane key="1" tab="老师" force-render>
            <a-tree
              v-model="checkedTeacherList"
              :tree-data="teacherList"
              checkable
              @check="onTeacherChange"
            ></a-tree>
          </a-tab-pane>
          <a-tab-pane key="2" tab="学生" force-render>
            <a-tree
              v-model="checkedStudentList"
              :tree-data="studentList"
              checkable
              @check="onStudentChange"
            ></a-tree>
          </a-tab-pane>
          <!-- <a-tab-pane key="3" tab="角色" force-render>
            <a-checkbox-group v-model="checkedRoleList" @change="onRoleChange">
              <a-row>
                <a-col :span="24" v-for="item in roleList" :key="item.roleCode">
                  <a-checkbox :value="item.roleCode">
                    {{ item.roleName }}
                  </a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group>
          </a-tab-pane> -->
        </a-tabs>
      </div>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: "AddTeacherTree",
  data() {
    return {
      teacherList: [],
      checkedTeacherList: [],
      selectedTeacherList: [],

      studentList: [],
      checkedStudentList: [],
      selectedStudentList: [],

      roleList: [],
      checkedRoleList: [],
      selectedRoleList: [],
    };
  },

  mounted() {
    console.log('执行addmenber');
    this.getModinMemberList();
    this.getworkflowroleList();
    this.getmodianGradetreeAndAllUser();
  },
  watch: {
    selectedTeacherList: {
      handler(list) {
        this.$emit("teacherChange", list);
      },
      deep: true,
    },
    selectedStudentList: {
      handler(list) {
        this.$emit("studentChange", list);
      },
      deep: true,
    },
    selectedRoleList: {
      handler(list) {
        this.$emit("roleChange", list);
      },
      deep: true,
    },
  },

  methods: {
    ...mapActions("controlPage", [
      "postallTeacherAndTree",
      "workflowroleList",
      "modianGradetreeAndAllUser",
    ]),
    //查找所有父节点  返回id集合
    getParentIds(list, id) {
        for (let i in list) {
          if (list[i].id === id || list[i].userId === id) {
            return [];
          }
          if (list[i].children) {
            let node = this.getParentIds(list[i].children, id);
            if (node) {
              return node.concat(list[i].id);
            }
          }
        }
      },
    // getParentKey(key, tree) {
    //   let parentKey;
    //   for (let i = 0; i < tree.length; i++) {
    //     const node = tree[i];

    //     if (node.children) {
    //       if (node.children.some((item) => item.key === key)) {
    //         parentKey = node.key;
    //       } else if (this.getParentKey(key, node.children)) {
    //         parentKey = this.getParentKey(key, node.children);
    //       }
    //     }
    //   }

    //   return parentKey;
    // },
    async getModinMemberList() {
      let r = await this.postallTeacherAndTree();
      if (r.message === "success") {
        this.handleTreeData(r.data.departmentTree);
        this.teacherList = r.data.departmentTree;
      } else {
        this.$message.warning(r.message);
      }
    },
    handleTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        const { id, userId, name, child, personList } = item;
        item.title = name;
        item.key = id || userId;
        item.children = child && child.length ? child : personList;
        if ((child && child.length) || (personList && personList.length)) {
          this.handleTreeData(child && child.length ? child : personList);
        }
      }
    },
    studentTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        const { id, userId, name, child, studentMiniVos } = item;
        item.title = name;
        item.key = id || userId;
        item.children = child && child.length ? child : studentMiniVos;
        if (
          (child && child.length) ||
          (studentMiniVos && studentMiniVos.length)
        ) {
          this.studentTreeData(child && child.length ? child : studentMiniVos);
        }
      }
    },
    async getmodianGradetreeAndAllUser() {
      let r = await this.modianGradetreeAndAllUser();
      if (r.message === "success") {
        // this.teacherList = r.data.teacherList;
        // 学生列表
        this.studentTreeData(r.data.list);
        this.studentList = r.data.list;
      } else {
        this.$message.warning(r.message);
      }
    },

    // 角色
    async getworkflowroleList() {
      let params = {
        // pageNo: this.pagination.pageIndex,
        // pageSize: this.pagination.pageSize,
      };
      let r = await this.workflowroleList(params);
      let { code, data, message } = r;
      if (code === 0) {
        this.roleList = data.list;
      } else {
        this.$message.warning(message);
      }
    },
    onStudentChange(checkedValues, checkedNodes) {
      this.checkedStudentList = checkedValues;
      let arr = [];
      checkedNodes.checkedNodesPositions.forEach((item) => {
        const { name, userId, userIndex, gradeId, child, studentMiniVos } =
          item.node.data.props;
        if (!child || !studentMiniVos) {
          arr.push({
            userName: name,
            userId,
            userIndex,
            gradeId,
            userType: "S",
          });
        }
      });
      this.selectedStudentList = arr;
    },
    onTeacherChange(checkedValues, checkedNodes) {
      this.checkedTeacherList = checkedValues;
      let arr = [];
      checkedNodes.checkedNodesPositions.forEach((item) => {
        const { name, userId, userIndex, departmentId, child, personList } =
          item.node.data.props;
        if (!child || !personList) {
          arr.push({
            userName: name,
            userId,
            userIndex,
            departmentId,
            userType: "T",
          });
        }
      });
      this.selectedTeacherList = arr;
    },
    onRoleChange(checkedValues) {
      this.checkedRoleList = checkedValues;
      let arr = [];
      checkedValues.forEach((item) => {
        const obj = this.roleList.find((v) => v.roleCode === item);
        arr.push(obj);
      });
      this.selectedRoleList = arr;
    },
    // 获取魔点人员信息列表
    async getcheckedStudentList() {
      let params = {
        pageNo: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize,
      };
      let r = await this.checkedStudentList(params);
      let { code, data, message } = r;
      if (code === 0) {
        this.dataSource = data.list;
        this.pagination.total = data.total;
      } else {
        this.$message.warning(message);
      }
    },
    delCheckedEvt(userId, type) {
      if (type === "T") {
        const result = this.getParentIds(this.teacherList, userId)
           console.log("mmmm",result)
        this.selectedTeacherList = this.selectedTeacherList.filter(
          (v) => v.userId !== userId
        );
        this.checkedTeacherList = this.checkedTeacherList.filter(
          (v) => v !== userId && !result.includes(v)
        );
      } else if (type === "S") {
        const result = this.getParentIds(this.studentList, userId)
           console.log("mmmm",result)
        this.selectedStudentList = this.selectedStudentList.filter(
          (v) => v.userId !== userId
        );
        this.checkedStudentList = this.checkedStudentList.filter(
          (v) => v !== userId && !result.includes(v)
        );

      } else {
        this.selectedRoleList = this.selectedRoleList.filter(
          (v) => v.roleCode !== userId
        );
        this.checkedRoleList = this.checkedRoleList.filter((v) => v !== userId);
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import url("./common.less");
.add-teacher-tree {
  display: flex;
  width: 640px;
  height: 356px;
  margin: -24px 0;
  .left {
    flex: 1;
    height: 350px;
    .title {
      height: 40px;
      line-height: 40px;
    }
    .custom-scrollbar();
    border-right: 1px solid #e5e5e5;
    .checked-area {
      margin: 12px 0;
      .item {
        display: inline-flex;
        align-items: center;
        height: 32px;
        text-align: center;
        line-height: 32px;
        background: #f2f4f5;
        margin: 6px 12px;
        margin-left: 0;
        border-radius: 4px;
        padding: 0 12px;
        user-select: none;
        color: #999;
        &:hover {
          color: #666;
          background: #e5e5e5;
        }

        .label {
          display: inline-block;
          max-width: 120px;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          color: #333;
          font-size: 14px;
          font-weight: 400;
          margin-right: 8px;
        }
        .icon {
          cursor: pointer;
        }
      }
    }
    .search-area {
      margin-left: 0px;
    }
  }
  .right {
    width: 300px;
    padding: 0 20px;
    border-left: 1px solid #e8e8e8;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 0;
    }
  }
}
</style>
